from flask import Flask
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_mail import Mail
from . import config
from .models import db
import os
import logging
from logging.handlers import RotatingFileHandler

# 初始化扩展
cors = CORS()
jwt = JWTManager()
mail = Mail()

def create_app(config_name='development'):
    """应用工厂函数"""
    app = Flask(__name__)
    
    # 加载配置
    app.config.from_object(config.config[config_name])
    
    # 初始化扩展
    cors.init_app(app)
    db.init_app(app)
    jwt.init_app(app)
    mail.init_app(app)
    
    # 注册蓝图
    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
        
        # 初始化默认用户
        from .models import User
        user = User.query.filter_by(username='admin').first()
        if not user:
            user = User(username='admin', role='系统管理员')
            user.set_password('123456')
            db.session.add(user)
            db.session.commit()
    
    # 配置日志
    if not app.debug and not app.testing:
        if not os.path.exists('logs'):
            os.mkdir('logs')
        
        file_handler = RotatingFileHandler(
            'logs/ai_decision_system.log', 
            maxBytes=10240, 
            backupCount=10
        )
        
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
        ))
        
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)
        app.logger.setLevel(logging.INFO)
        app.logger.info('路口信控数智融合AI决策系统启动')
    
    return app